package com.example.constellation.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.example.constellation.bean.StarBean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AssetsUtils {
    //读取assets文件的字符串方法
    public static String getString(Context context,String filename){
        //获取assets文件管理器
        AssetManager am = context.getResources().getAssets();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //打开文件 获取文件输入流
        try {
            InputStream inputStream=am.open(filename);
            //读取内容存放到内存流中
            int hasread=0;
            byte[] buf=new byte[1024];
            while (true){
                hasread=inputStream.read(buf);
                if (hasread==-1){
                    break;
                }
                baos.write(buf,0,hasread);
            }
            String msg = baos.toString();
            inputStream.close();
            return msg;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //读取assets图片方法 返回bitmap
    public static Bitmap getbitmap(Context context,String filename){
        Bitmap bitmap=null;
        //获取assets文件管理器
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream inputStream=am.open(filename);
            //通过位图管理器，将输入流转化为位图对象
            bitmap= BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //读取文件夹中的图片，放在内存中
    private static Map<String,Bitmap>logoimgmap;
    private static Map<String,Bitmap>contentlogomap;

    public static void savelogomap(Context context, StarBean starinfoBean){
        logoimgmap=new HashMap<>();
        contentlogomap=new HashMap<>();
        List<StarBean.StarinfoBean>  starlist = starinfoBean.getStarinfo();
        for (int i=0;i<starlist.size();i++){
            String logoname = starlist.get(i).getLogoname();
            String filename="xzlogo/"+logoname+".png";
            Bitmap logobm = getbitmap(context, filename);
            logoimgmap.put(logoname,logobm);
            String contentname="xzcontentlogo/"+logoname+".png";
            Bitmap contentbm = getbitmap(context, contentname);
            contentlogomap.put(logoname,contentbm);
        }
    }

    public static Map<String, Bitmap> getContentlogomap() {
        return contentlogomap;
    }

    public static Map<String, Bitmap> getLogoimgmap() {
        return logoimgmap;
    }
}
